import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/good/ui/good_all_page.dart';
import 'package:shopping_group/modle/good/ui/good_complete_page.dart';
import 'package:shopping_group/modle/good/ui/good_do_page.dart';
import 'package:shopping_group/modle/good/ui/good_doing_page.dart';
import 'package:shopping_group/modle/good/ui/good_paly_do_page.dart';
import 'package:shopping_group/modle/login/ui/user_auth_page.dart';
import 'package:shopping_group/modle/login/ui/user_modify_password_page.dart';
import 'package:shopping_group/modle/person/bloc/my_money_bloc.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/shared_preferences_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';
import 'package:shopping_group/view/combination_view.dart';
import 'package:shopping_group/modle/person/ui/about_page.dart';
import '../../../res/dimens.dart';
import 'bind_phone_page.dart';
import 'change_daili_page.dart';
import 'change_money_view_page.dart';
import 'my_adress_page.dart';

class PersonPage extends StatefulWidget {
  @override
  _PersonPageState createState() => _PersonPageState();
}

class _PersonPageState extends State<PersonPage>
    with AutomaticKeepAliveClientMixin {
  StreamSubscription _colorSubscription;
  String _allAccount = '0';
  String _reBuyQuanAcct = '0';
  String _jfAcct = '0';
  String _nlqAcct = '0';
  String _jinTieAcct = '0';
  String _phone = '';
  String _name = '';
  bool _isRealNameAuthen = false;
  MyMoneyBloc _myMoneyBloc;
  StreamSubscription _resetMoneySubscription;
  String version = BaseConstant.VERSION;
  @override
  void initState() {
    super.initState();
    _myMoneyBloc = MyMoneyBloc();

    //订阅eventbus
    _colorSubscription = eventBus.on<BlackSjEvent>().listen((event) {
      setState(() {
        _allAccount = BaseConstant.dsAllAcct;
        _phone = BaseConstant.code;
        _name = BaseConstant.name;
        _reBuyQuanAcct = BaseConstant.reBuyQuanAcct;
        _isRealNameAuthen = BaseConstant.isRealNameAuthen;
        _jfAcct = BaseConstant.jfAcct;
        _nlqAcct = BaseConstant.nlqAcct;
        _jinTieAcct = BaseConstant.jinTieAcct;
      });
    });

    _resetMoneySubscription = eventBus.on<ResetMoneyEvent>().listen((event) {
      if (BaseConstant.isLogin) {
        _myMoneyBloc.initDate.add(null);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          height: double.infinity,
          decoration: new BoxDecoration(
            color: Colours.transparent,
          ),
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            reverse: false,
            padding: EdgeInsets.all(0.0),
            physics: BouncingScrollPhysics(),
            child: showPersonalView(),
          ),
        ),
      ),
    );
  }

  Widget showPersonalView() {
    return Column(
      children: <Widget>[
        showUserIcon(),
        SizedBox(
          height: 8,
        ),
        showBottom(),
      ],
    );
  }

  Widget showBottom() {
    return Utils.isWeixin()
        ? Container()
        : Padding(
            padding: const EdgeInsets.only(top: 16),
            child: ButtonProgressView.crateCupertinoView('退出登录',
                cupertinoCall: () {
              // if (BaseConstant.isLogin) {
              _loginOut();
              // } else {
              //   RouteUtil.goView(PageConstance.LOGIN_PAGE);
              // }
            }),
          );
  }

  Future _loginOut() async {
    showDialog(
        context: context,
        builder: (context) {
          return showAlertDialog();
        }).then((var result) {
      if (null == result) {
        return;
      }
      if (result is String && 'yes' == result) {
        _clear();
      }
    });
  }

  _clear() {
    setState(() {
      BaseConstant.isLogin = false;
      BaseConstant.code = '';
      BaseConstant.name = '';
      BaseConstant.nickname = '';
      BaseConstant.idCard = '';
      BaseConstant.token = '';
      BaseConstant.capitalAccount = '0';
      BaseConstant.integralAccount = '0';
      BaseConstant.allAccount = '0';
      BaseConstant.dsAllAcct = '0';
      BaseConstant.reBuyQuanAcct = '0';
      BaseConstant.jfAcct = '0';
      BaseConstant.fuliAcct = '0';
      BaseConstant.nlqAcct = '0';
      BaseConstant.adressEntity = SouJianRenEntity();
      BaseConstant.changePageIndex = 0;
      BaseConstant.weixinOperId = '';
      SharedPreferencesUtil.addShare('password', '');
      SharedPreferencesUtil.addShare('userEntity', '');
      BaseConstant.isUpdate = false;
      eventBus.fire(ToChangePageEvent());
    });
  }

  Widget showAlertDialog() {
    return AlertDialog(
      title:
          WidgetUtils.getTextColorView('选择', Colors.black, Dimens.FONT_SIZE_18),
      content: WidgetUtils.getTextColorView(
          '是否退出？', Colors.black, Dimens.FONT_SIZE_16),
      actions: <Widget>[
        FlatButton(
          onPressed: () {
            Navigator.of(context).pop('yes');
          },
          child: WidgetUtils.getTextColorView(
              '确定', Colors.black, Dimens.FONT_SIZE_16),
        ),
        FlatButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: WidgetUtils.getTextColorView(
                '取消', Colors.black, Dimens.FONT_SIZE_16))
      ],
    );
  }

  Widget showUserIcon() {
    return Stack(
      children: <Widget>[
        Container(
          height: 240,
          color: Colours.themeColor,
        ),
        Container(
            margin: EdgeInsets.only(top: 80),
            child: Column(
              children: <Widget>[
                GestureDetector(
                  onTap: () {},
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        padding: const EdgeInsets.only(
                          top: 0,
                          left: 32,
                        ),
                        child: Icon(
                          Icons.account_circle,
                          size: 64,
                          color: Colors.white70,
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.only(left: 16),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            WidgetUtils.getTextColorView(
                                //BaseConstant.shopStarName
                                'ID:$_phone   ',
                                Colors.white,
                                Dimens.FONT_SIZE_16),
                            SizedBox(
                              height: 4,
                            ),
                            ObjectUtil.isEmptyString(_name)
                                ? Container()
                                : WidgetUtils.getTextColorView(
                                    //BaseConstant.starLevelName
                                    '姓名:$_name   ',
                                    Colors.white,
                                    Dimens.FONT_SIZE_16),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: Dimens.FONT_SIZE_16,
                ),
                _myOrder(),
                SizedBox(
                  height: Dimens.FONT_SIZE_8,
                ),
                _getKfView(),
                SizedBox(
                  height: Dimens.FONT_SIZE_8,
                ),
                _mainView(),
                SizedBox(
                  height: Dimens.FONT_SIZE_8,
                ),
                _aboutView(),
              ],
            )),
      ],
    );
  }

//我的订单
  Widget _myOrder() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: Dimens.FONT_SIZE_16),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.title_white, width: 1.0),
          borderRadius: BorderRadius.circular(10.0),
          color: Colours.title_white),
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(GoodAllPage());
            },
            child: CombinationView.showItmeView(null, '全部订单',
                content: '全部订单',
                isHideConten: false,
                isHideIcon: true,
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
          WidgetUtils.drawDivider(),
          Container(
              decoration: new BoxDecoration(
                color: Colors.white,
              ),
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 32),
              child: Flex(
                direction: Axis.horizontal,
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        RouteUtil.goParameter(GoodPalyToPage());
                      },
                      child: Container(
                        color: Colors.transparent,
                        child: Column(
                          children: <Widget>[
                            Icon(
                              Icons.call_to_action,
                              color: Colours.themeColor,
                              size: 32,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 8),
                              child: WidgetUtils.getTextColorView('待付款',
                                  Colours.text_2222, Dimens.FONT_SIZE_16),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        RouteUtil.goParameter(GoodToPage());
                      },
                      child: Container(
                          color: Colors.transparent,
                          child: Column(
                            children: <Widget>[
                              Icon(
                                Icons.airport_shuttle,
                                color: Colours.themeColor,
                                size: 32,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(top: 8),
                                child: WidgetUtils.getTextColorView('待发货',
                                    Colours.text_2222, Dimens.FONT_SIZE_16),
                              ),
                            ],
                          )),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        RouteUtil.goParameter(GoodToingPage());
                      },
                      child: Container(
                          color: Colors.transparent,
                          child: Column(
                            children: <Widget>[
                              // WidgetUtils.buildNetworkImageView(
                              //     'https://static.jiujiupingou.com/Static/images/be_received.png',
                              //     width: 32,
                              //     height: 32),
                              Icon(
                                Icons.archive,
                                color: Colours.themeColor,
                                size: 32,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(top: 8),
                                child: WidgetUtils.getTextColorView('待收货',
                                    Colours.text_2222, Dimens.FONT_SIZE_16),
                              ),
                            ],
                          )),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        RouteUtil.goParameter(GoodCompletePage());
                      },
                      child: Container(
                          color: Colors.transparent,
                          child: Column(
                            children: <Widget>[
                              // WidgetUtils.buildNetworkImageView(
                              //     'https://static.jiujiupingou.com/Static/images/successful_transaction.png',
                              //     width: 32,
                              //     height: 32),
                              Icon(
                                Icons.assignment_turned_in,
                                color: Colours.themeColor,
                                size: 32,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(top: 8),
                                child: WidgetUtils.getTextColorView('交易成功',
                                    Colours.text_2222, Dimens.FONT_SIZE_16),
                              ),
                            ],
                          )),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  //关于
  Widget _aboutView() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: Dimens.FONT_SIZE_16),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.title_white, width: 1.0),
          borderRadius: BorderRadius.circular(10.0),
          color: Colours.title_white),
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(AboutDialogPage());
            },
            child: CombinationView.showItmeView(null, '关于利正生活',
                content: '版本号：$version',
                isHideConten: false,
                isHideIcon: true,
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
          WidgetUtils.drawDivider(),
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(UserModifyPassWordPage());
            },
            child: CombinationView.showItmeView(null, '修改密码',
                isHideIcon: true,
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

//客服中心
  Widget _getKfView() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: Dimens.FONT_SIZE_16),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.title_white, width: 1.0),
          borderRadius: BorderRadius.circular(10.0),
          color: Colours.title_white),
      child: Column(
        children: <Widget>[
          CombinationView.showItmeView(null, '客服中心',
              content: '竭诚为您服务',
              isHideConten: false,
              isHideIcon: true,
              blackColor: Colours.transparent,
              titleFontweight: FontWeight.w500),
          WidgetUtils.drawDivider(),
          CombinationView.showItmeView(null, '投诉中心',
              content: '问题与反馈',
              isHideConten: false,
              isHideIcon: true,
              blackColor: Colours.transparent,
              titleFontweight: FontWeight.w500),
        ],
      ),
    );
  }

  //主要菜单
  Widget _mainView() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: Dimens.FONT_SIZE_16),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.title_white, width: 1.0),
          borderRadius: BorderRadius.circular(10.0),
          color: Colours.title_white),
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(MyAdressPage());
            },
            child: CombinationView.showItmeView(Icons.location_on, '地址管理',
                content: '',
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
          WidgetUtils.drawDivider(),
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(ChangeDaiLiPage());

              // HttpUtilAll.post(Apis.AUC_COMMO_URL,
              //     data: {"val": "COMT_MUST_BUY", "pageIndex": "1", "pageSize": "20"},
              //     headers: {'token': BaseConstant.token}, success: (result) {
              //   print("result == ${result}");
              // }, error: (errorMsg) {
              //   BotToast.closeAllLoading();
              //   // 请求失败返回的错误信息
              //   BotToast.showText(text: errorMsg);
              // }); //GSF_ID_4_DS
            },
            child: CombinationView.showItmeView(Icons.group, '我的团友',
                content: '',
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
          WidgetUtils.drawDivider(),
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(ChangeViewMoneyPage());
            },
            child: CombinationView.showItmeView(
                Icons.account_balance_wallet, '账户余额',
                content: '¥' + _allAccount,
                isHideConten: false,
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
          WidgetUtils.drawDivider(),
          // GestureDetector(
          //   onTap: () {
          //     RouteUtil.goParameter(JiFenViewPage());
          //   },
          //   child: CombinationView.showItmeView(
          //       Icons.airline_seat_recline_normal, '积分',
          //       content: '$_jfAcct',
          //       isHideConten: false,
          //       blackColor: Colours.transparent,
          //       titleFontweight: FontWeight.w500),
          // ),
          // WidgetUtils.drawDivider(),
          // GestureDetector(
          //   onTap: () {
          //     RouteUtil.goParameter(NliangQuanViewPage());
          //   },
          //   child: CombinationView.showItmeView(Icons.menu, '能量券',
          //       content: '$_nlqAcct',
          //       isHideConten: false,
          //       blackColor: Colours.transparent,
          //       titleFontweight: FontWeight.w500),
          // ),
          // WidgetUtils.drawDivider(),
          // GestureDetector(
          //   onTap: () {
          //     RouteUtil.goView(PageConstance.FUGOU_VIEW_PAGE);
          //   },
          //   child: CombinationView.showItmeView(Icons.loyalty, '复购券',
          //       content: '$_reBuyQuanAcct',
          //       isHideConten: false,
          //       blackColor: Colours.transparent,
          //       titleFontweight: FontWeight.w500),
          // ),
          // WidgetUtils.drawDivider(),
          // GestureDetector(
          //   onTap: () {
          //     RouteUtil.goParameter(ChangeJintieViewPage());
          //   },
          //   child: CombinationView.showItmeView(Icons.account_balance, '津贴',
          //       content: _jinTieAcct,
          //       isHideConten: false,
          //       blackColor: Colours.transparent,
          //       titleFontweight: FontWeight.w500),
          // ),
          WidgetUtils.drawDivider(),
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(BindPhonePage());
            },
            child: CombinationView.showItmeView(Icons.undo, '绑定手机号',
                content: '',
                isHideConten: false,
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
          WidgetUtils.drawDivider(),
          GestureDetector(
            onTap: () {
              RouteUtil.goParameter(UserAuthPage());
            },
            child: CombinationView.showItmeView(Icons.assignment_ind, '实名认证',
                content: _isRealNameAuthen ? '已认证' : '未认证',
                isHideConten: false,
                blackColor: Colours.transparent,
                titleFontweight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _colorSubscription?.cancel();
    //_newSubscription?.cancel();
    _resetMoneySubscription?.cancel();
  }

  @override
  bool get wantKeepAlive => true;
}
